"""
收藏相关API - 集成WebSocket推送
"""
from fastapi import APIRouter, Depends, HTTPException, status, Request
from sqlalchemy.orm import Session
from starlette.concurrency import run_in_threadpool
from typing import List

from utils.database import get_db
from utils import JWTUtils
from Models.travel.models import Favorite, Attraction
from Views.home.websocket.ws_notifier import (
    notify_favorite_added,
    notify_favorite_removed
)
from pydantic import BaseModel

router = APIRouter(prefix="/travel/favorites", tags=["收藏管理"])


def get_current_user_id(request: Request) -> int:
    """从请求头获取当前用户ID"""
    authorization = request.headers.get("Authorization")
    if not authorization:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="未提供认证令牌"
        )
    
    token = authorization.replace("Bearer ", "").strip()
    payload = JWTUtils.decode_access_token(token)
    if not payload or not payload.get("user_id"):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="认证令牌无效"
        )
    return payload["user_id"]


class FavoriteInfo(BaseModel):
    """收藏信息"""
    id: int
    user_id: int
    attraction_id: int
    attraction_name: str = None
    attraction_image: str = None
    attraction_price: float = None
    created_at: str
    
    class Config:
        from_attributes = True


class FavoriteListResponse(BaseModel):
    """收藏列表响应"""
    total: int
    page: int
    page_size: int
    favorites: List[FavoriteInfo] = []


@router.post("/{attraction_id}", summary="添加收藏")
async def add_favorite(
    attraction_id: int,
    request: Request,
    db: Session = Depends(get_db)
):
    """添加收藏"""
    user_id = get_current_user_id(request)
    
    def _add_favorite():
        # 检查景点是否存在
        attraction = db.query(Attraction).filter(
            Attraction.id == attraction_id,
            Attraction.is_active == True
        ).first()
        
        if not attraction:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="景点不存在"
            )
        
        # 检查是否已收藏
        existing = db.query(Favorite).filter(
            Favorite.user_id == user_id,
            Favorite.attraction_id == attraction_id
        ).first()
        
        if existing:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="已收藏该景点"
            )
        
        # 创建收藏
        favorite = Favorite(
            user_id=user_id,
            attraction_id=attraction_id
        )
        
        db.add(favorite)
        db.commit()
        db.refresh(favorite)
        
        return favorite, attraction
    
    favorite, attraction = await run_in_threadpool(_add_favorite)
    
    # 发送收藏通知
    notify_favorite_added(
        user_id=user_id,
        attraction_id=attraction_id,
        attraction_name=attraction.name
    )
    
    return {
        "message": "收藏成功",
        "favorite_id": favorite.id,
        "attraction_name": attraction.name
    }


@router.delete("/{attraction_id}", summary="取消收藏")
async def remove_favorite(
    attraction_id: int,
    request: Request,
    db: Session = Depends(get_db)
):
    """取消收藏"""
    user_id = get_current_user_id(request)
    
    def _remove_favorite():
        # 查找收藏记录
        favorite = db.query(Favorite).filter(
            Favorite.user_id == user_id,
            Favorite.attraction_id == attraction_id
        ).first()
        
        if not favorite:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="未收藏该景点"
            )
        
        # 获取景点信息（用于通知）
        attraction = db.query(Attraction).filter(
            Attraction.id == attraction_id
        ).first()
        
        attraction_name = attraction.name if attraction else "未知景点"
        
        # 删除收藏
        db.delete(favorite)
        db.commit()
        
        return attraction_name
    
    attraction_name = await run_in_threadpool(_remove_favorite)
    
    # 发送取消收藏通知
    notify_favorite_removed(
        user_id=user_id,
        attraction_id=attraction_id,
        attraction_name=attraction_name
    )
    
    return {"message": "取消收藏成功", "attraction_name": attraction_name}


@router.get("", response_model=FavoriteListResponse, summary="获取收藏列表")
async def get_favorites(
    page: int = 1,
    page_size: int = 10,
    request: Request = None,
    db: Session = Depends(get_db)
):
    """获取当前用户的收藏列表"""
    user_id = get_current_user_id(request)
    
    def _get_favorites():
        query = db.query(Favorite).filter(Favorite.user_id == user_id)
        
        total = query.count()
        favorites = query.order_by(Favorite.created_at.desc()).offset(
            (page - 1) * page_size
        ).limit(page_size).all()
        
        # 加载景点信息
        for favorite in favorites:
            if favorite.attraction:
                favorite.attraction_name = favorite.attraction.name
                favorite.attraction_image = favorite.attraction.cover_image
                favorite.attraction_price = favorite.attraction.price
        
        return total, favorites
    
    total, favorites = await run_in_threadpool(_get_favorites)
    
    return FavoriteListResponse(
        total=total,
        page=page,
        page_size=page_size,
        favorites=[FavoriteInfo.model_validate(f) for f in favorites]
    )


@router.get("/check/{attraction_id}", summary="检查是否已收藏")
async def check_favorite(
    attraction_id: int,
    request: Request,
    db: Session = Depends(get_db)
):
    """检查是否已收藏"""
    user_id = get_current_user_id(request)
    
    def _check():
        favorite = db.query(Favorite).filter(
            Favorite.user_id == user_id,
            Favorite.attraction_id == attraction_id
        ).first()
        return favorite is not None
    
    is_favorited = await run_in_threadpool(_check)
    return {"is_favorited": is_favorited}








